"use strict";

const express = require("express"),
	router = express.Router(),
	bcrypt = require('bcryptjs'),
	jwt = require('jsonwebtoken'),
	keys = require("../../config/index"),
	passport = require("passport"),
	nedb = require('nedb');

const db = new nedb({
	filename: 'database/user.db',
	autoload: true
});

/**
 * @api {get} /api/user 获取全部
 * @apiGroup user
 * @apiSuccess {json} result
 * @apiVersion 1.0.0
 * @apiSampleRequest /api/user
 * @apiSuccessExample Success-Response:
 * {
 * 	"result": []
 *	"message": null,
 * 	"code": 0,
 * 	"status": 200
 * }
 */

router.get("/", async (req, res) => {
	db.findOne({ name: /req.query.name/ }, (err, ret) => {
		res.tools.setJson(ret || [])
	})
})


router.post("/", async (req, res) => {
	// 查询数据库中是否拥有邮箱
	const user = await db.findOne({ email: req.body.email })
	if (user) return res.tools.setJson('', '邮箱已经存在', 20005)
	const newUser = new User({
		name: req.body.name,
		email: req.body.email,
		password: req.body.password,
		createTime: req.body.createTime
	})
	bcrypt.genSalt(10, (err, salt) => {
		bcrypt.hash(newUser.password, salt, async (err, hash) => {
			// hash为加密后的密码
			if (err) throw err;
			newUser.password = hash;
			const saveUser = await newUser.save()
			res.tools.setJson(saveUser)
		});
	})
})

module.exports = router;